package com.woniu.defecttracking.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.defecttracking.commens.ComUtil;
import com.woniu.defecttracking.entity.Account;
import com.woniu.defecttracking.entity.AccountDetails;
import com.woniu.defecttracking.mapper.ResourceMapper;
import com.woniu.defecttracking.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class LoadAccountServiceImpl implements UserDetailsService {

    @Autowired
    private AccountService accountService;
    @Autowired
    private StringRedisTemplate srt;
    @Resource
    private ResourceMapper resourceMapper;
    @Resource
    private RedisTemplate rtl;

    /**
    * @作者: 倪西
    * @描述：登录验证，将账号对应的url和账号信息存入redis中临时保存
    * @时间：2022/1/7 22:19
    * @参数：[s]
    * @返回：org.springframework.security.core.userdetails.UserDetails
    **/
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        Account account = accountService.getOne(new QueryWrapper<Account>().eq("account_name", s));
        if (null==account){
            throw new UsernameNotFoundException("该账号不存在");
        }
        AccountDetails accountDetails = ComUtil
                .copyProperties(account, AccountDetails.class);

        List<String> uriList = resourceMapper.selectResourceByAccount(accountDetails.getAccountId());
        srt.opsForList().leftPushAll("resource:url:accountId:"+accountDetails.getAccountId(),uriList);
        srt.expire("resource:url:accountId:"+accountDetails.getAccountId(),2, TimeUnit.HOURS);

        rtl.opsForValue().set("account:info:id:" + accountDetails.getAccountId(),account,2,TimeUnit.HOURS);
        return accountDetails;
    }
}
